//
(function(){

  var ps = "absolute";

  //创建蛇的构造函数
  function Snake(option){
    option = option instanceof Object ? option : {};
    //给对象添加属性
    //设置蛇节的宽度和高度
    this.width = option.width || 20;
    this.height = option.height || 20;
    //设置蛇身
    this.body = [
      {x:3, y:2, color:"red"},
      {x:2, y:2, color:"blue"},
      {x:1, y:2, color:"blue"}
    ]
    //设置移动方向 right,top,left,bottom
    this.direction = "right";
    //存储渲染的所有元素
    this.elements = [];
  }

  //添加一个将元素渲染到页面上的方法
  Snake.prototype.render = function(map){
    //生成对应的div元素
    var length = this.body.length;
    for(var i = 0; i < length; i++){
      //根据数组中的每一项的数据生成div元素
      var piece = this.body[i];
      //创建新元素
      var ele = document.createElement("div");
      ele.style.width = this.width + "px";
      ele.style.height = this.height + "px";
      ele.style.left = piece.x * this.width + "px";
      ele.style.top = piece.y * this.height + "px";
      ele.style.position = ps;
      ele.style.backgroundColor = piece.color;
      //渲染到指定的父级内部
      map.appendChild(ele);
      //添加的新元素添加到数组中
      this.elements.push(ele);
    }
  }

  Snake.prototype.remove = function(map){
    //将元素从map中删除
    for(var i = this.elements.length -1 ; i >= 0; i--){
      map.removeChild(this.elements[i]);
    }
    this.elements = [];
  }

  //蛇运动
  Snake.prototype.move = function(){
    //蛇身的每一节都要变成上一节的位置
    for(var i = this.body.length - 1; i > 0; i--){
      this.body[i].x = this.body[i-1].x;
      this.body[i].y = this.body[i-1].y;
    }
    //定义蛇头
    var head = this.body[0];  
    
    switch (this.direction) {
      case "right":
        head.x += 1;
        break;
      case "left":
        head.x -= 1;
        break;
      case "top":
        head.y -= 1;
        break;
      case "bottom":
        head.y += 1;
        break;
    }
  }

  window.Snake = Snake;
})();

// var map = document.getElementById("map");
// var snake = new Snake();
// snake.render(map);